package com.platform.boot.security.filter;

import com.platform.boot.security.ReactiveSecurityHelper;
import com.platform.boot.security.ReactiveSecurityUserHolder;
import lombok.RequiredArgsConstructor;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * @author Alex bob(<a href="https://github.com/vnobo">https://github.com/vnobo</a>)
 */
@RequiredArgsConstructor
public class ExchangeContextFilter implements WebFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        return exchange.getSession().flatMap(session -> chain.filter(exchange)
                .contextWrite(ReactiveSecurityUserHolder.withSecurityDetails(
                        session.getAttribute(ReactiveSecurityHelper.SECURITY_TOKEN_CONTEXT))));
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}